package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.domain.UserFollow;
import com.domain.UserTestEntity;
import com.exception.ConditionException;
import com.mapper.UserFollowDao;
import com.mapper.UserTestMapper;
import com.service.UserTestService;
import com.util.RSAUtil;
import com.util.StringUtils;
import com.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表简化 服务实现类
 * </p>
 *
 * @author sly
 * @since 2024-01-10
 */
@Service
public class UserTestServiceImpl extends ServiceImpl<UserTestMapper, UserTestEntity> implements UserTestService {

    @Autowired
    private UserTestMapper userTestMapper;

    @Autowired
    private UserFollowDao userFollowDao;

    @Override
    public void register(UserTestEntity userTestEntity) throws Exception {
        String username = userTestEntity.getUserName();
        String password = userTestEntity.getPassword();
        String msg = "";
        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < 2 || username.length() > 20) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < 5 || password.length() > 20) {
            msg = "密码长度必须在5到20个字符之间";
        }
        QueryWrapper<UserTestEntity> userTestQueryWrapper = new QueryWrapper<>();
        userTestQueryWrapper.lambda().eq(UserTestEntity::getUserName, username).eq(UserTestEntity::getIsDel, 0);
        UserTestEntity userExists = userTestMapper.selectOne(userTestQueryWrapper);
        if (userExists != null) {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        if (msg.isEmpty()) {
            userTestEntity.setNickName(username);
            userTestEntity.setPassword(RSAUtil.encrypt(password));
            userTestEntity.setCreateTime(new Date());
            userTestEntity.setIsDel(0);
            userTestMapper.insert(userTestEntity);
        } else {
            throw new ConditionException(msg);
        }
    }

    @Override
    public String login(UserTestEntity userTestEntity) throws Exception {
        String username = userTestEntity.getUserName();
        String password;
        try {
            password = RSAUtil.decrypt(userTestEntity.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ConditionException("密码解密失败!");
        }
        String msg = "";
        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < 2 || username.length() > 20) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < 5 || password.length() > 20) {
            msg = "密码长度必须在5到20个字符之间";
        }
        if (!msg.isEmpty()) {
            throw new ConditionException(msg);
        }
        QueryWrapper<UserTestEntity> userTestQueryWrapper = new QueryWrapper<>();
        userTestQueryWrapper.lambda().eq(UserTestEntity::getUserName, userTestEntity.getUserName())
                .eq(UserTestEntity::getIsDel, 0);
        UserTestEntity userExists = userTestMapper.selectOne(userTestQueryWrapper);
        if (userExists == null) {
            throw new ConditionException("当前用户不存在，请确认您输入的用户名是否正确！");
        }
        // 返回token令牌
        return TokenUtil.generateToken(userExists.getId());
    }

    @Override
    public UserTestEntity getUserInfo(Long userId) {
        // 查询详情
        UserTestEntity userTestEntity = userTestMapper.getUserInfo(userId);
        return userTestEntity;
    }

    @Override
    public UserTestEntity getUserDetail(Long userId, Long MyUserId) {
        // 查询个人配置
        QueryWrapper<UserTestEntity> userTestQueryWrapper = new QueryWrapper<>();
        userTestQueryWrapper.lambda().eq(UserTestEntity::getId, userId)
                .eq(UserTestEntity::getIsDel, 0);
        UserTestEntity userTestEntity = userTestMapper.selectOne(userTestQueryWrapper);
        // 获取总播放量
        List<Integer> userVideoInfo = userTestMapper.getUserVideoInfo(userId);
        userTestEntity.setVideoPlayCount(userVideoInfo.stream().mapToInt((x) -> x).sum());
        // 获取总被收藏数
        userTestEntity.setVideoCollectionCount(userTestMapper.getUserVideoColectionCount(userId));
        // 是否已经关注
        QueryWrapper<UserFollow> userFollowQueryWrapper = new QueryWrapper<>();
        userFollowQueryWrapper.lambda().eq(UserFollow::getUserId, MyUserId)
                .eq(UserFollow::getFollowId, userId);
        UserFollow isFollowEach = userFollowDao.selectOne(userFollowQueryWrapper);
        if (isFollowEach != null) {
            userTestEntity.setHasFollow(1);
        }
        return userTestEntity;
    }

    @Override
    public void updateUser(UserTestEntity userTestEntity) {
        userTestEntity.setUpdateTime(new Date());
        userTestMapper.updateById(userTestEntity);
    }
}
